package net.tngou.jtdb.netty;



import java.io.IOException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import net.tngou.db.util.ResultSet;
import net.tngou.db.util.SerializationUtils;
import net.tngou.jtdb.util.ConfigurationUtil;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;


public class TngouClient {

	 
	private static Log log = LogFactory.getLog(TngouClient.class);
	private Channel channel=null;//链接信息
	private ClientHandler clh=new ClientHandler();
	private EventLoopGroup group = new NioEventLoopGroup();
	private ConfigurationUtil config = ConfigurationUtil.getInstance();
	public TngouClient()
	{		
		 Bootstrap boot = new Bootstrap();
		 boot.group(group)
		 .channel(NioSocketChannel.class)
		  .option(ChannelOption.TCP_NODELAY, true)
		  .handler(new ChannelInitializer<SocketChannel>() {
			  @Override
			  public void initChannel(SocketChannel ch) throws Exception {
				ChannelPipeline pipeline = ch.pipeline();
			  	pipeline.addLast(new ObjectEncoder());
			  	pipeline.addLast(new ObjectDecoder(ClassResolvers.cacheDisabled(null)));
			  	pipeline.addLast(clh);		  	
			  }			
		  });		
	   try {			   
			    channel = boot.connect(config.getHost(), config.getPort()).sync().channel();
			    log.debug("建立服务器连接-"+config.getHost()+":"+config.getPort());
			   
		} catch (InterruptedException  e) {
			log.error("连接服务器-"+config.getHost()+":"+config.getPort()+" 失败");
		}
	 }
	 
	 
	 
	 public ResultSet exe(String sql) {
		 ChannelFuture cf = null;
		 ResultSet res= new ResultSet();
		 res.setMsg(sql);
		 ResultSet response =null;
		 try {
			 byte[] bytes = SerializationUtils.serialize(res);
			 cf = channel.writeAndFlush(bytes);
			 cf.sync();
			 response=clh.getResponse();
			 //等待
			 for (int i = 0; i < config.getOvertime()&&response==null; i++) {
				 Thread.sleep(1);
				 response=clh.getResponse();
			}		
			clh.clearResponse();
		} catch (IOException | InterruptedException e) {
			log.error("请求执行语句{"+sql+"}错误!");
			return new ResultSet(ResultSet.T_ERROR_CONNECT);//链接服务错误	
		}
		if(response==null) return new ResultSet(ResultSet.T_SUCCESS_NULL);	//返回数据为空	 
		return response;
	}
	 
	 
	 
	 /**
	  * 关闭连接池
	 * @throws
	  */
	 public void close() {
		 group.shutdownGracefully();
		 log.debug("关闭连接");
	}
	 
	 


 
 
 
	
}
